import { deletePublicize, listPublicize, selectPublicizeById } from '@/api/modules/lcd/publicize';
import { allowEditMenu, query, table } from '../data/data';
import { form, resetForm } from './form';
import { notify } from '@/utils/common/common';
import dayjs from 'dayjs';

const dateFormat = 'YYYY-MM-DD HH:mm:ss';
export const create = () => {
  allowEditMenu.value = true;
  resetForm();
};
export const list = async () => {
  table.value.loading = true;
  const { data } = await listPublicize(query.value);
  table.value.data = data.rows;
  table.value.loading = false;
  query.value.total = data.total;
};

export const edit = async (id?: string) => {
  const targetId = id ? id : table.value.keys[0];
  const { data } = await selectPublicizeById(targetId);
  let result = data.data;
  form.value = result;
  form.value.week = result.week.split(',');
  console.log(form.value.publishTime);

  form.value.publishTime = result.publishTime.map(e => {
    if (e.time?.length > 0) {
      e.time = [dayjs(e.time[0], dateFormat), dayjs(e.time[1], dateFormat)];
    }
    console.log(e.time);

    return e;
  });
  allowEditMenu.value = true;
  table.value.loading = false;
};

export const remove = async (id?: string) => {
  const ids = id ? [id] : table.value.keys;
  const { data } = await deletePublicize(ids);
  notify(data);
  await list();
};

export const detail = () => {
  allowEditMenu.value = true;
  table.value.loading = false;
};
export const search = () => {
  query.value.pageNum = 1;
  list();
};
